<template>
  <div>
    <!--面包屑导航区域-->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片布局区域-->
    <el-card>
      <!--卡片栅格 搜索与添加区域-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryList.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!--用户列表区域-->
      <el-table :data="userLiset" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!--修改按钮-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!--删除按钮-->
            <el-tooltip effect="dark" content="删除" placement="top" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!--分配角色按钮-->
            <el-tooltip effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini"></el-button>
            </el-tooltip>

          </template>
        </el-table-column>
      </el-table>
      <!--分页区域-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryList.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!--添加对话框-->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50% " @close="addDialogClose">
      <!--对话框主体-->
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--修改对话框-->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50% " @close="editDialogClose">
      <!--对话框主体-->
      <el-form :model="editForm" :rules="addRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--删除对话框-->
    <el-dialog
      title="删除用户"
      :visible.sync="deleteDialogVisible"
      width="30% ">
      <!--对话框主体-->
      <span>确定永久删除用户吗?</span>
      <!--对话框底部区域-->
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="deleteUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      let checkEmail = (rule,value,cb) =>{
        const regEmail = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
        if (regEmail.test(value)){
          return cb()
        }
        cb(new Error('请输入合法邮件'))
      }
      let checkMobile = (rule,value,cb) =>{
        const regMobile = /^1[3456789]\d{9}$/
        if (regMobile.test(value)){
          return cb()
        }
        cb(new Error('请输入合法手机号'))
      }
      return {
        queryList: {
          query: '',
          // 当前页数
          pagenum: 1,
          pagesize: 2
        },
        userLiset: [],
        total: 0,
        //添加框显示隐藏
        dialogVisible: false,
        // 修改框显示与隐藏
        editDialogVisible:false,
        //删除框显示与隐藏
        deleteDialogVisible:false,
        //添加用户的数据对象
        addForm:{
          username:'',
          password:'',
          email:'',
          mobile:''

        },
        //修改用户id查询所得数据
        editForm:{},
        //删除用户id查询数据
        deleteForm:{},
        //添加用户的验证对象
        addRules:{
          username:[
            { required: true, message: '请输入用户名称', trigger: 'blur' },
            { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
          ],
          password:[
            { required: true, message: '请输入用户密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
          ],
          email:[
            { required: true, message: '请输入邮箱', trigger: 'blur' },
            { validator: checkEmail,trigger: 'blur'}
          ],
          mobile:[
            { required: true, message: '请输入手机', trigger: 'blur' },
            { validator: checkMobile,trigger: 'blur'}
          ]
        }
      }
    },
    created () {
      this.getUserList()
    },
    methods: {
      async getUserList () {
        const { data: res } = await this.$http.get('users', { params: this.queryList })
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败')
        }
        this.userLiset = res.data.users
        this.total = res.data.total
        console.log(res)
      },
      // 监听pagesuze改变事件
      handleSizeChange (newSize) {
        // console.log(newSize)
        this.queryList.pagesize = newSize
        this.getUserList()
      },
      // 监听页码值改变事件
      handleCurrentChange (newPage) {
        // console.log(newPage)
        this.queryList.pagenum = newPage
        this.getUserList()
      },
      //用户状态改变
      async userStateChange (userInfo) {
        // console.log(userInfo)
        const { data: res } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          userInfo.mg_state = !userInfo.mg_state
          return this.$message.error('修改数据失败')
        }
        this.$message.success('修改数据成功')
      },
      //监听对话框关闭事件
      addDialogClose(){
        this.$refs.addFormRef.resetFields()
      },
      //点击后验证合法性后提交
      addUser(){
        this.$refs.addFormRef.validate(async valid =>{
          if (!valid)return
          const {data:res} = await this.$http.post('users',this.addForm)
          if (res.meta.status !== 201) {
            this.$message.error('提交失败')
          }
          this.$message.success('提交成功')
          this.dialogVisible = false
          this.getUserList()
        })
      },
      //监听对话框关闭事件
      editDialogClose(){
        this.$refs.editFormRef.resetFields()
      },
      //监听修改对话框打开事件
      async showEditDialog(id){
        const {data:res} = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) {
          this.$message.error('提交失败')
        }
        this.editForm = res.data
        this.editDialogVisible = true
      },
      //修改对话框提交
      async editUser(){
        this.$refs.editFormRef.validate(async valid =>{
          if (!valid)return
          const {data:res} = await this.$http.put(`users/${this.editForm.id}`,{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          })
          if (res.meta.status !== 200) {
            this.$message.error('提交失败')
          }
          this.$message.success('提交成功')
          this.editDialogVisible = false
          this.getUserList()
        })
      },
      //监听删除对话框打开事件
      async deleteEditDialog(id){
        const {data:res} = await this.$http.get(`users/${id}`)
        if (res.meta.status !== 200) {
          this.$message.error('提交失败')
        }
        this.deleteForm = res.data
        this.deleteDialogVisible = true
      },
      //修改对话框提交
      async deleteUser(){
        const {data:res} = await this.$http.delete(`users/${this.deleteForm.id}`)
        if (res.meta.status !== 200) {
          this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.editDialogVisible = false
        this.getUserList()
      },
    }
  }
</script>

<style scoped>
</style>
